<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    

    <title>
      原型链 | 江月夜 
    </title>

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    
      <meta name="author" content="江月夜">
    
    

    <meta name="description" content="创建对象的几种方法123456789101112// 1.使用new Object()var o1 = new Object(&amp;#123;name: &apos;o1&apos;&amp;#125;);// 2.对象字面量 (这种方法其实就是第一种的简写)var o2 = &amp;#123;name: &ap">
<meta name="keywords" content="前端">
<meta property="og:type" content="article">
<meta property="og:title" content="原型链 | 江月夜">
<meta property="og:url" content="http://yoursite.com/2018/09/27/prototype/index.html">
<meta property="og:site_name" content="江月夜">
<meta property="og:description" content="创建对象的几种方法123456789101112// 1.使用new Object()var o1 = new Object(&amp;#123;name: &apos;o1&apos;&amp;#125;);// 2.对象字面量 (这种方法其实就是第一种的简写)var o2 = &amp;#123;name: &apos;o2&apos;&amp;#125;;// 3.构造函数var A = function(name) &amp;#123;  this.name = na">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/images/proto.png">
<meta property="og:image" content="http://yoursite.com/images/instanceof.png">
<meta property="og:updated_time" content="2018-10-29T09:07:23.582Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="原型链 | 江月夜">
<meta name="twitter:description" content="创建对象的几种方法123456789101112// 1.使用new Object()var o1 = new Object(&amp;#123;name: &apos;o1&apos;&amp;#125;);// 2.对象字面量 (这种方法其实就是第一种的简写)var o2 = &amp;#123;name: &apos;o2&apos;&amp;#125;;// 3.构造函数var A = function(name) &amp;#123;  this.name = na">
<meta name="twitter:image" content="http://yoursite.com/images/proto.png">
    
    
    
      <link rel="icon" type="image/x-icon" href="/favicon.png">
    
    <link rel="stylesheet" href="/css/uno.css">
    <link rel="stylesheet" href="/css/highlight.css">
    <link rel="stylesheet" href="/css/archive.css">
    <link rel="stylesheet" href="/css/china-social-icon.css">

</head>
<body>

    <span class="mobile btn-mobile-menu">
        <i class="icon icon-list btn-mobile-menu__icon"></i>
        <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i>
    </span>

    

<header class="panel-cover panel-cover--collapsed">


  <div class="panel-main">

  
    <div class="panel-main__inner panel-inverted">
    <div class="panel-main__content">

        

        <h1 class="panel-cover__title panel-title"><a href="/" title="link to homepage">江月夜</a></h1>
        <hr class="panel-cover__divider" />

        
        <p class="panel-cover__description">
          腹有诗书气自华
        </p>
        <hr class="panel-cover__divider panel-cover__divider--secondary" />
        

        <div class="navigation-wrapper">

          <nav class="cover-navigation cover-navigation--primary">
            <ul class="navigation">

              
                
                <li class="navigation__item"><a href="/#blog" title="" class="blog-button">首页</a></li>
              
                
                <li class="navigation__item"><a href="/about" title="" class="">关于</a></li>
              
                
                <li class="navigation__item"><a href="/archive" title="" class="">归档</a></li>
              

            </ul>
          </nav>

          <!-- ----------------------------
To add a new social icon simply duplicate one of the list items from below
and change the class in the <i> tag to match the desired social network
and then add your link to the <a>. Here is a full list of social network
classes that you can use:

    icon-social-500px
    icon-social-behance
    icon-social-delicious
    icon-social-designer-news
    icon-social-deviant-art
    icon-social-digg
    icon-social-dribbble
    icon-social-facebook
    icon-social-flickr
    icon-social-forrst
    icon-social-foursquare
    icon-social-github
    icon-social-google-plus
    icon-social-hi5
    icon-social-instagram
    icon-social-lastfm
    icon-social-linkedin
    icon-social-medium
    icon-social-myspace
    icon-social-path
    icon-social-pinterest
    icon-social-rdio
    icon-social-reddit
    icon-social-skype
    icon-social-spotify
    icon-social-stack-overflow
    icon-social-steam
    icon-social-stumbleupon
    icon-social-treehouse
    icon-social-tumblr
    icon-social-twitter
    icon-social-vimeo
    icon-social-xbox
    icon-social-yelp
    icon-social-youtube
    icon-social-zerply
    icon-mail

-------------------------------->

<!-- add social info here -->



<nav class="cover-navigation navigation--social">
  <ul class="navigation">

    
      <!-- Github -->
      <li class="navigation__item">
        <a href="https://github.com/ajiu9" title="">
          <i class='icon icon-social-github'></i>
          <span class="label">GitHub</span>
        </a>
      </li>
    

    <!-- China social icon -->
    <!--
    
      <li class="navigation__item">
        <a href="" title="">
          <i class='icon cs-icon-douban'></i>
          <span class="label">Douban</span>
        </a>
      </li>

      <li class="navigation__item">
        <a href="" title="">
          <i class='icon cs-icon-weibo'></i>
          <span class="label">Weibo</span>
        </a>
      </li>

    -->



  </ul>
</nav>



        </div>

      </div>

    </div>

    <div class="panel-cover--overlay"></div>
  </div>
</header>

    <div class="content-wrapper">
        <div class="content-wrapper__inner entry">
            

<article class="post-container post-container--single">

  <header class="post-header">
    
    <h1 class="post-title">原型链</h1>

    

    <div class="post-meta">
      <time datetime="2018-09-27" class="post-meta__date date">2018-09-27</time> 

      <span class="post-meta__tags tags">

          
            <font class="categories">
            &#8226; 分类:
            <a class="categories-link" href="/categories/原型链/">原型链</a>
            </font>
          

          
             &#8226; 标签:
            <font class="tags">
              <a class="tags-link" href="/tags/前端/">前端</a>
            </font>
          

      </span>
    </div>
    
    

  </header>

  <section id="post-content" class="article-content post">
    <h4 id="创建对象的几种方法"><a href="#创建对象的几种方法" class="headerlink" title="创建对象的几种方法"></a>创建对象的几种方法</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.使用new Object()</span></span><br><span class="line"><span class="keyword">var</span> o1 = <span class="keyword">new</span> <span class="built_in">Object</span>(&#123;<span class="attr">name</span>: <span class="string">'o1'</span>&#125;);</span><br><span class="line"><span class="comment">// 2.对象字面量 (这种方法其实就是第一种的简写)</span></span><br><span class="line"><span class="keyword">var</span> o2 = &#123;<span class="attr">name</span>: <span class="string">'o2'</span>&#125;;</span><br><span class="line"><span class="comment">// 3.构造函数</span></span><br><span class="line"><span class="keyword">var</span> A = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> o3 = <span class="keyword">new</span> A(<span class="string">'o3'</span>);</span><br><span class="line"><span class="comment">// 4.Object.create()</span></span><br><span class="line"><span class="keyword">var</span> B = &#123;<span class="attr">name</span>: <span class="string">'o4'</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> o4 = <span class="built_in">Object</span>.create(B);</span><br></pre></td></tr></table></figure>
<h4 id="构造函数、原型、实例、原型链"><a href="#构造函数、原型、实例、原型链" class="headerlink" title="构造函数、原型、实例、原型链"></a>构造函数、原型、实例、原型链</h4><p>JavaScript是一门面向对象基于原型继承的语言,那么原型到底是怎么实现继承的？<br><img src="/images/proto.png" alt=""><br>prototype原型是一个对象，只有函数才有的属性，这是在创建函数是js引擎自动添加的属性，其他对象可以通过它实现属性继承。<br><code>__proto__</code>是每个对象都有的属性，但不是一个规范属性，它指向的是构造函数的原型对象。(<code>__proto__</code>通过上面第四种方式<code>Object.create(O))</code>指向的是对象O)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.创建构造函数Animal</span></span><br><span class="line"><span class="keyword">var</span> Animal = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.name = name</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 2.实例化一个对象dog</span></span><br><span class="line"><span class="keyword">var</span> dog = <span class="keyword">new</span> Animal(<span class="string">'dog'</span>);</span><br><span class="line"><span class="comment">// Animal 构造函数的原型的constructor属性指向构造函数本身</span></span><br><span class="line">Animal.prototype.constructor === Animal <span class="comment">// true</span></span><br><span class="line"><span class="comment">// dog实例的__proto__指向构造函数的原型</span></span><br><span class="line">dog.__proto__ === Animal.prototype <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p>原型链指由于<code>__proto__</code>是对象都有的属性，所以会形成一条由<code>__proto__</code>连起来的链条，递归访问<code>__proto__</code>最终到终点，最后指向<code>null</code>.<br>当js查找对象的属性时，先查找对象本身有没有这个属性，如果不存在，就会在原型链上查找，直到找到或者到达终点的<code>null</code>。</p>
<h4 id="instanceof运算符"><a href="#instanceof运算符" class="headerlink" title="instanceof运算符"></a>instanceof运算符</h4><p><code>instanceof</code>运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置<br><img src="/images/instanceof.png" alt=""><br>用<code>instanceof</code>来判断实例对象是否为构造函数直接生成的对象并不严格，因为出现在对象原型链中任何位置都会返回true，这时可以使用对象的<code>__proto__.constructor</code>是否严格等于构造函数来判断。<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 测试构造函数的prototype属性是否出现在对象的原型链中</span></span><br><span class="line">dog <span class="keyword">instanceof</span> Animal; <span class="comment">// true</span></span><br><span class="line">dog <span class="keyword">instanceof</span> <span class="built_in">Object</span>; <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 判断实例对象是否为构造函数直接生成</span></span><br><span class="line">dog.__proto__.constructor === Animal; <span class="comment">// true</span></span><br></pre></td></tr></table></figure></p>
<h4 id="new-运算符"><a href="#new-运算符" class="headerlink" title="new 运算符"></a>new 运算符</h4><p>执行new后</p>
<ul>
<li>一个新对象被创建，它继承自构造函数foo.prototype</li>
<li>构造函数foo被执行。执行的时候，相应的参数被传入，同时上下文<code>this</code>会被指定为这个新实例。 <code>new foo</code> 等于 <code>new foo()</code>,只能用在不传递任何参数的情况下。</li>
<li>如果构造函数返回了一个对象，那么这个对象会整个取代new出来的结果。如果构造函数没有返回对象，那么new出来的结果为第一步创建的对象。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// new 的执行如下</span></span><br><span class="line"><span class="keyword">var</span> new1 = <span class="function"><span class="keyword">function</span>(<span class="params">func</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 第一步:一个新对象被创建，它继承自构造函数func.prototype</span></span><br><span class="line">  <span class="keyword">var</span> o = <span class="built_in">Object</span>.create(func.prototype);</span><br><span class="line">  <span class="comment">// 第二步：构造函数func被执行。执行的时候，相应的参数被传入，同时上下文`this`会被指定为这个新实例。</span></span><br><span class="line">  <span class="keyword">var</span> k = func.call(o);</span><br><span class="line">  <span class="comment">// 第三步</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> k === <span class="string">'object'</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> k</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> o</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 验证new内部原理是否和new1函数的执行过程一样</span></span><br><span class="line"><span class="comment">//构造函数</span></span><br><span class="line"><span class="keyword">var</span> A = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// new运算符</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> o3 = <span class="keyword">new</span> A(<span class="string">'o3'</span>);</span><br><span class="line"><span class="comment">// new1()</span></span><br><span class="line"><span class="keyword">var</span> o6 = new1(A);</span><br><span class="line"><span class="comment">// 接下来验证通过new1生成的o6对象是否和new生成的o3一样</span></span><br><span class="line">o6 <span class="keyword">instanceof</span> A; <span class="comment">// true</span></span><br><span class="line">o6 <span class="keyword">instanceof</span> <span class="built_in">Object</span>; <span class="comment">// true</span></span><br><span class="line">o6.__proto__.constructor === A; <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line">A.prototype.walk= <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;<span class="built_in">console</span>.log(<span class="string">'walk'</span>)&#125;</span><br><span class="line">o6.walk() <span class="comment">// walk</span></span><br><span class="line">o3.walk() <span class="comment">// walk</span></span><br></pre></td></tr></table></figure>
<p>通过上面的代码可以看出，new的执行原理了吧。</p>

  </section>

  <section class="post-comments">

   <!--PC和WAP自适应版-->
<div id="SOHUCS" sid="请将此处替换为配置SourceID的语句" ></div> 
<script type="text/javascript"> 
(function(){ 
var appid = 'cytl2q04G'; 
var conf = 'prod_c6e77c75d2d767714e129c11e500044d'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    
</section>


</article>


            <footer class="footer">

    <span class="footer__copyright">&copy; 2017 | 由<a href="https://hexo.io/">Hexo</a>| 主题<a href="https://github.com/someus/huno">Huno</a></span>
    
</footer>
        </div>
    </div>

    <!-- js files -->
    <script src="/js/jquery.min.js"></script>
    <script src="/js/main.js"></script>
    <script src="/js/scale.fix.js"></script>
    

    

    <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <script type="text/javascript"> 
        $(document).ready(function(){
            MathJax.Hub.Config({ 
                tex2jax: {inlineMath: [['[latex]','[/latex]'], ['\\(','\\)']]} 
            });
        });
    </script>


    

    <script src="/js/awesome-toc.min.js"></script>
    <script>
        $(document).ready(function(){
            $.awesome_toc({
                overlay: true,
                contentId: "post-content",
            });
        });
    </script>


    
    
    <!--kill ie6 -->
<!--[if IE 6]>
  <script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script>
<![endif]-->

</body>
</html>
